#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/10/29 22:41
# @Author  : Nabby
# @File    : user_manage.py
# @Desc    :

import hashlib
import uuid
from pprint import pprint, pformat
from collections import defaultdict
from infrastructure.po.impl.user_impl import UserImpl
from infrastructure.po.impl.role_impl import RoleImpl
from infrastructure.po.impl.role_resource_impl import RoleResourceImpl
from infrastructure.po.impl.resource_impl import ResourceImpl
from infrastructure.utils.http import responser
from infrastructure.utils.decorator.oauth2_tool import generate_token

class UserManage(object):
    @classmethod
    def get_user_list(cls, username=None, company_name=None, phone=None, email=None, page=1, page_size=999):
        """
        查询用户列表
        :param name: 查询
        :param page: 页码
        :param page_size: 每页数量
        :return:
        """
        response_data = []
        user_list, total = UserImpl.get_user_list(
            username=username,
            company_name=company_name,
            phone=phone,
            email=email,
            page=page,
            page_size=page_size
        )
        for user in user_list:
            # pprint(user.__dict__) 
            user_role = UserImpl.get_user_role(user.id)
            role = RoleImpl.get_role_by_id(user_role.role_id)
            response_data.append({
                "id": user.id,
                "username": user.username,
                "country": user.country,
                "companyName": user.company_name,
                "email": user.email,
                "phone": user.phone,
                "roleId": user_role.role_id,
                "roleName": role.name,
                "status": user.status,
                "createdAt": user.created_at,
                "updatedAt": user.updated_at
            })
        data = {
            "data": response_data,
            "total": total
        }
        return responser.send(10000, data=data)

    @classmethod
    def add_user(
            cls,
            username,
            country,
            companyName,
            phone,
            email,
            password,
            role_id,
    ):
        md = hashlib.md5()
        md.update(password.encode('utf-8'))
        password = md.hexdigest()
        user_code = UserImpl.add_user(
            id=str(uuid.uuid4()),
            role_id=role_id,
            username=username,
            phone=phone,
            country=country,
            companyName=companyName,
            email=email,
            password=password
        )
        if user_code:
            return responser.send(10000)
        else:
            return responser.send(10004)

    @classmethod
    def update_user(
            cls,
            id,
            username,
            country,
            companyName,
            phone,
            email,
            role_id,
    ):
        user_code = UserImpl.update_user(
            id=id,
            username=username,
            role_id=role_id,
            phone=phone,
            country=country,
            companyName=companyName,
            email=email
        )
        if user_code:
            return responser.send(10000)
        else:
            return responser.send(54001)

    @classmethod
    def update_user_password(
            cls,
            id,
            old_password,
            new_password
    ):
        """
        修改用户密码
        :param user_id: 用户id
        :param password: 密码
        :return:
        """
        user = UserImpl.get_user_by_id(id)
        if user:
            # md = hashlib.md5()
            # md.update(old_password.encode('utf-8'))
            # old_password = md.hexdigest()
            # print("user.password:" + user.password, flush=1)
            # print("old_password:" + old_password, flush=1)
            if user.password == old_password:
                # md = hashlib.md5()
                # md.update(new_password.encode('utf-8'))
                # new_password = md.hexdigest()
                UserImpl.update_user_password(
                    id,
                    password=new_password
                )
                return responser.send(10000)
            else:
                return responser.send(10005)
        else:
            return responser.send(10001)

    @classmethod
    def change_user_status(
            cls,
            user_id,
            status
    ):
        """
        变更用户状态
        :param user_id: 用户id
        :param status: 状态
        :return:
        """
        user = UserImpl.get_user_by_id(user_id)
        if user:
            UserImpl.change_user_status(
                user_id=user_id,
                status=status
            )
            return responser.send(10000)
        else:
            return responser.send(10001)

    @classmethod
    def delete_user(
            cls,
            user_id
    ):
        """
        删除用户
        :param user_id: 用户id
        :return:
        """
        UserImpl.delete_user(user_id=user_id)
        return responser.send(10000)

    @classmethod
    def login(cls, userName, password):
        print("=====login=====")
        # md = hashlib.md5()
        # md.update(password.encode('utf-8'))
        # password = md.hexdigest()
        user = UserImpl.get_user_by_name(userName)
        if user:
            if user.password == password:
                pprint(user.__dict__) 
                token = generate_token(user.id)
                user_role = UserImpl.get_user_role(user.id)
                role_resources = RoleResourceImpl.get_role_resource_by_role_id(user_role.role_id)
                print("role_resources:", role_resources)
                # 遍历资源列表，将资源的权限信息添加到data中
                resource_first_level_dict = {}
                resource_second_level_dict = {}
                for role_resource in role_resources:
                    # print("role_resource:", role_resource)
                    resource = ResourceImpl.get_resource_by_id(role_resource.resource_id)
                    print("resource:", resource.id, flush=1)
                    if resource.sys_resource_id is None:
                        resource_first_level_dict[role_resource.resource_id] = {
                            "children": [],
                            "menuCode": resource.perms,
                            "menuName": resource.name,
                            "menuOrder": resource.seq
                        }
                    else:
                        children = []
                        resource_second_level_dict[role_resource.resource_id] = {
                            **({"children": children} if children else {}),
                            "menuCode": resource.perms,
                            "menuName": resource.name,
                            "menuOrder": resource.seq,
                            "parentId": resource.sys_resource_id
                        }
                for key, value in resource_second_level_dict.items():
                    parent_id = value["parentId"]
                    if parent_id in resource_first_level_dict:
                        del value["parentId"]
                        print("value:", value, flush=1)
                        resource_first_level_dict[parent_id]["children"].append(value)
                print("resource_first_level_dict:", resource_first_level_dict, flush=1)

                data = {
                    "token": token,
                    "userId": user.id,
                    "userName": user.username,
                    "country": user.country,
                    "companyName": user.company_name,
                    "email": user.email,
                    "phone": user.phone,
                    "roleId": user_role.role_id,
                    "rolePermission": list(resource_first_level_dict.values()),
                }
                return responser.send(10000, data=data)
            else:
                return responser.send(10002)
        else:
            return responser.send(10001)